/**
 * 
 */
package com.wy2.generator.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


import com.wy2.generator.config.GeneratorConsts;

/**
 * freemarker 工具类
 * @author nnsword
 * @date 2017-12-17 17:28:00
 *
 */
public class FreemarkerUtils {

	public final static String FILE_TAG_PATTERN="__([^_]*)__";
	public final static String FREEMARKER_BEGIN="${";
	public final static String FREEMARKER_END="}";
	
	public static Boolean isFileTag(String fileTag) {
		Pattern pattern = Pattern.compile(FILE_TAG_PATTERN);
		Matcher matcher = pattern.matcher(fileTag);
		return matcher.matches();
	}
	/**
	 *  将自定义文件标签字符串转换为freemarker模板内容，如: __fileName__ 转换为 ${fileName}
	 *  因freemarker的标签无法在文件路径中使用，故设计了此变种标签
	 * @date 2017-12-17 17:43:30
	 * @param tag
	 * @return
	 */
	public static String customTagConvert(String tag) {
		Pattern pattern = Pattern.compile(FILE_TAG_PATTERN);
		Matcher matcher = pattern.matcher(tag);
		StringBuilder resultSb=new StringBuilder();
		int pos=0,count;
		while(matcher.find()) {
			count=matcher.groupCount();
			if(count == 1) {
				if(pos==0) {
					resultSb.append(tag.substring(pos,matcher.start()));
					resultSb.append(FREEMARKER_BEGIN);
					resultSb.append(matcher.group(1));
					resultSb.append(FREEMARKER_END);
					
				}else {
					resultSb.append(tag.substring(pos,matcher.start()));
					resultSb.append(FREEMARKER_BEGIN);
					resultSb.append(matcher.group(1));
					resultSb.append(FREEMARKER_END);
				}
				pos=matcher.end();
				
			}
		}
		if (pos < tag.length()) {
			resultSb.append(tag.substring(pos));
		}
		return resultSb.toString();
	}
	
	/**
	 *  字符模板 编码，获得 模板名称
	 * @date 2017-12-22 01:13:29
	 * @param templateContent
	 * @return
	 */
	public static final String stringTemplateEncode(String templateContent) {
		return GeneratorConsts.STRING_TEMPLATE_NAME_PREFIX+templateContent;
	}
	/**
	 * 字符模板 解码，获得 模板内容
	 * @date 2017-12-22 01:15:25
	 * @param templateName
	 * @return
	 */
	public static final String stringTemplateDecode(String templateName) {
		if(!templateName.startsWith(GeneratorConsts.STRING_TEMPLATE_NAME_PREFIX)) {
			return templateName;
		}
		return templateName.substring(GeneratorConsts.STRING_TEMPLATE_NAME_PREFIX.length());
	}
	
	
	public static void main(String[] args) {
		String result=FreemarkerUtils.customTagConvert("templates/__basePackages__/__table.entityName__.java.ftl");
		System.out.println(result);
	}
}
